SIMPLEGUICS2PYGAME with Python

Manish Patel

18-July-2023

INSTALL SIMPLEGUICS2PYGAME


python -m pip install SimpleGUICS2Pygame --user

Note - Restart kernel after installation

IMPORT SIMPLEGUICS2PYGAME

import SimpleGUICS2Pygame.simpleguics2pygame as simplegui 

Why SIMPLEGUI?

EVENT DRIVEN PROGRAMMING

  • It is the programming paradigm where the flow of the program is primarily determined by user actions or events. In this paradigm, the program waits for specific events to occur and then responds accordingly.

EVENT

PROGRAM STRUCTURE

FRAME

  • A frame is a window, which is a container for the controls, status information, and canvas. A program can create only one frame.

CREATE FRAME

START FRAME

EXAMPLE

import SimpleGUICS2Pygame.simpleguics2pygame as simplegui 

#frame = simplegui.create_frame(window_name, canvas_width, canvas_height)

frame = simplegui.create_frame("New Frame", 200, 300)

# Here are the parts of the frame:
# window_name = "New Frame"
# canvas_width = 200
# canvas_height = 300

frame.start()

CANVAS

COLORS

GET CANVAS TEXT WIDTH

EXAMPLE

import SimpleGUICS2Pygame.simpleguics2pygame as simplegui 

frame = simplegui.create_frame('Testing', 100, 100)
print(frame.get_canvas_textwidth('hello', 12))
print(frame.get_canvas_textwidth('hello', 12, 'sans-serif'))
print(frame.get_canvas_textwidth('hello1', 12, 'sans-serif'))

frame.start()
23
20
24
29

CONTROL OBJECTS

  • Control objects are placed in the control panel, which is the left-hand part of the frame. They are placed top-down in the order of creation. Status information is at the bottom of the control panel.

OPERATIONS

ADD LABEL TO FRAME CONTROL PANEL

ADD BUTTON TO FRAME CONTROL PANEL

A sample program that allows the user to change the color of the canvas using buttons.

import SimpleGUICS2Pygame.simpleguics2pygame as simplegui

# Global variables
canvas_color = "White"

# Event handlers
def button_handler_red():
    global canvas_color
    canvas_color = "Red"

def button_handler_green():
    global canvas_color
    canvas_color = "Green"

def button_handler_blue():
    global canvas_color
    canvas_color = "Blue"

def draw(canvas):
    canvas.draw_polygon([(0, 0), (200, 0), (200, 200), (0, 200)], 0, canvas_color, canvas_color)

# Create a frame
frame = simplegui.create_frame("Change Canvas Color", 200, 200)

# Create buttons
button_red = frame.add_button("Red", button_handler_red)
button_green = frame.add_button("Green", button_handler_green)
button_blue = frame.add_button("Blue", button_handler_blue)

# Set the draw handler
frame.set_draw_handler(draw)

# Start the frame
frame.start()

TRUE FALSE QUIZ

# Buttons
# True / False Quiz


# This is a sample program that creates a simple 5 question
#   True / False quiz. You can change the number and type
#   of questions to create your own!
# Note: This is not the most efficient way to design this
#   program. A better implementation uses lists, but we 
#   haven't learned about those yet. Watch for an improved
#   version of this program in week 4!

import SimpleGUICS2Pygame.simpleguics2pygame as simplegui 

# Global Variables

canvas_color = "Black"
canvas_width = 300
canvas_height = 300

question_number = 1
cur_question = ""   # Keeps track of the current question
cur_answer = True   # Keeps track of the answer to the current question
player_answer = False
points = 0

question_1 = "'R' comes before 'Q' in the alphabet."
answer_1 = False
question_2 = "Africa is a continent."
answer_2 = True
question_3 = "Indentation is not important in CodeSkulptor."
answer_3 = False
question_4 = "5 + 2 * 3 = 21"
answer_4 = False
question_5 = "Computer Science is AWESOME!!!"
answer_5 = True

# Alternate set of "questions" - impossible quiz style
# Uncomment to use
#question_1 = "Zebra."
#answer_1 = False
#question_2 = "Apple Juice."
#answer_2 = True
#question_3 = "Happy."
#answer_3 = True
#question_4 = "Exponent."
#answer_4 = False
#question_5 = "Potato."
#answer_5 = True

# Helper Functions

def print_question():
    print "Question", question_number
    print cur_question

def check_answer():
    global points, cur_question, question_number, cur_answer
    if player_answer == cur_answer:
        print "Correct! Good job!"
        points += 1
        next_question()
    else:
        print "Incorrect"
        next_question()

def next_question():
    global cur_question, cur_answer, question_number
    if cur_question == question_1:
        cur_question = question_2
        cur_answer = answer_2
        question_number += 1
        print_question()
    elif cur_question == question_2:
        cur_question = question_3
        cur_answer = answer_3
        question_number += 1
        print_question()
    elif cur_question == question_3:
        cur_question = question_4
        cur_answer = answer_4
        question_number += 1
        print_question()
    elif cur_question == question_4:
        cur_question = question_5
        cur_answer = answer_5
        question_number += 1
        print_question()
    else:
        print "End of questions!"
        print "You scored:", points, "out of", question_number
        new_game()

# Event Handlers

def true_button():
    global player_answer
    player_answer = True
    check_answer()

def false_button():
    global player_answer
    player_answer = False
    check_answer()
    
def new_game():
    global cur_question, points, question_number, cur_answer
    cur_question = question_1
    cur_answer = answer_1
    points = 0
    question_number = 1
    print
    print "New Game! Good luck!"
    print_question()

# Frame

frame = simplegui.create_frame("Quiz", canvas_width, canvas_height) 

# Register Event Handlers

frame.add_button("True", true_button, 60)
frame.add_button("False", false_button, 60)
frame.add_button("Restart", new_game, 60)

# Start Frame and Game

new_game()
frame.start()

ADD TEXT INPUT BOX TO FRAME CONTROL PANEL

EXAMPLE

"""
Input field examples
"""

# Input fields can be used to call functions multiple times
#   while the program is running. Here are functions from
#   week one that can now be called using input fields.
#   There is a difference: input fields always return strings,
#   but the methods require numbers. This is solved using the
#   int() and float() methods.
# Remember to hit 'enter' after typing data into the input
#   fields to give it to the computor. Be careful! If you
#   enter the wrong type of data, an error can occur.

import SimpleGUICS2Pygame.simpleguics2pygame as simplegui 

# Constatns
CANVAS_WIDTH = 300
CANVAS_HEIGHT = 300

# Input handlers

def num_diagonals(num_sides):
    """
    Given integer num_sides, print number of diagonal for
    convex polygon with that number of sides
    """
    num_sides = int(num_sides)
    ans = num_sides * (num_sides - 3) // 2
    print("Number of Diagonals:")
    print(ans)
    print()

def print_triangle_type(degrees):
    """
    Given its largest angle in degrees, prints the type of triangle
    """
    degrees = float(degrees)
    print("Triangle Type:")
    if degrees > 90 and degrees < 180:
        print("Triangle is obtuse!")
    elif degrees == 90:
        print("Triangle is right!")
    elif degrees < 90 and degrees > 0:
        print("Triangle is acute!")
    else:
        print("Triangle does not exist!")
    print()
        
    
# Create frame
frame = simplegui.create_frame("Functions", CANVAS_WIDTH, CANVAS_HEIGHT, 150) 

# Register input handlers
frame.add_input("Number of sides:", num_diagonals, 100)
frame.add_input("Angle measure: (degrees)", print_triangle_type, 100)

# Start frame
frame.start()
Triangle Type:
Triangle is right!

GET CONTROL OBJECT TEXT

SET CONTROL OBJECT TEXT

KEYBOARD HANDLER

KEYBOARD CHARACTER CONSTANTS

EXAMPLE

"""
Demo of keyboard echo
"""

import SimpleGUICS2Pygame.simpleguics2pygame as simplegui 

# initialize state
current_key = ' '

# event handlers
def keydown(key):
    """
    Key down handler
    """
    global current_key
    current_key = chr(key)

def keyup(key):
    """
    Key up handler
    """
    global current_key
    current_key = ' '
    
def draw(canvas):
    """
    Draw handler, takes canvas as input
    """
    canvas.draw_text(current_key, [10, 25], 20, "Yellow")
    
# create frame
frame = simplegui.create_frame("Echo", 35, 35)

# register event handlers
frame.set_keydown_handler(keydown)
frame.set_keyup_handler(keyup)
frame.set_draw_handler(draw)

# start frame
frame.start()

MOUSE HANDLER

MOUSE CLICK EXAMPLE

"""
Demo of mouse click handler
"""

import SimpleGUICS2Pygame.simpleguics2pygame as simplegui 
import math

# intialize globals
WIDTH = 450
HEIGHT = 300
ball_pos = [WIDTH / 2, HEIGHT / 2]

BALL_RADIUS = 15
ball_color = "Red"

# helper function
def distance(pt1, pt2):
    """
    Take points pt1 and pt2 (as tuples)
    Return Euclidean distance between points
    """
    return math.sqrt( (pt1[0] - pt2[0]) ** 2 + (pt1[1] - pt2[1]) ** 2)

# define event handler for mouse click, draw
def click(pos):
    """
    Mouse click handler
    Updates ball color to green if click is inside ball,
    Otherwise moves ball to clicked position
    """
    global ball_pos, ball_color
    if distance(pos, ball_pos) < BALL_RADIUS:
        ball_color = "Green"
    else:
        ball_pos = list(pos)
        ball_color = "Red"

def draw(canvas):
    """
    Draw handler, with canvas as input
    """
    canvas.draw_circle(ball_pos, BALL_RADIUS, 1, "Black", ball_color)

# create frame
frame = simplegui.create_frame("Mouse selection", WIDTH, HEIGHT)
frame.set_canvas_background("White")

# register event handler
frame.set_mouseclick_handler(click)
frame.set_draw_handler(draw)

# start frame
frame.start()
    

MOUSE DRAG EXAMPLE

"""
Demo of mouse drag handler
"""


# This program allows the user to move a circle around the 
#   canvas using the mouse.

import SimpleGUICS2Pygame.simpleguics2pygame as simplegui 

# Global Variables

CANVAS_WIDTH = 300
CANVAS_HEIGHT = 300
point = [CANVAS_WIDTH / 2, CANVAS_HEIGHT / 2]

# Event Handlers
        
def draw(canvas):
    """
    Draw handler, takes canvas as input
    """
    canvas.draw_circle(point, 20, 5, "White", "Red")
    
# This is the handler for mouse drag events. Note that it
#   must take one parameter, a tuple of the position of the
#   mouse click.
def drag(pos):
    """
    Mouse drag handler, updates global variable point
    """
    global point
    point = pos
    
# Frame

frame = simplegui.create_frame("Ball Drag", CANVAS_WIDTH, CANVAS_HEIGHT) 

# Register Event Handlers

frame.set_draw_handler(draw)
# This is necessary to tell the program what to do with
#   mouse drag events
frame.set_mousedrag_handler(drag)

# Start
frame.start()

Hello World

import SimpleGUICS2Pygame.simpleguics2pygame as simplegui

def draw(canvas):
    canvas.draw_text("Hello, World!", (50, 50), 24, "White")

frame = simplegui.create_frame("Hello World", 200, 200)
frame.set_draw_handler(draw)

frame.start()

Interactive Button

import SimpleGUICS2Pygame.simpleguics2pygame as simplegui

def button_handler():
    print("Button clicked!")

frame = simplegui.create_frame("Interactive Button", 200, 200)
frame.add_button("Click me", button_handler)

frame.start()

Mouse Position

import SimpleGUICS2Pygame.simpleguics2pygame as simplegui

def mouse_handler(position):
    print("Mouse position:", position)

frame = simplegui.create_frame("Mouse Interaction", 200, 200)
frame.set_mouseclick_handler(mouse_handler)

frame.start()